package com.iteaj.iot.client;

import com.iteaj.network.IotProtocolFactory;
import com.iteaj.network.client.ClientMessage;
import com.iteaj.network.codec.IotMessageDecoder;
import com.iteaj.network.config.ConnectProperties;
import io.netty.channel.ChannelInboundHandler;

public class DefaultClientComponent extends TcpClientComponent {

    private String name;
    private String desc;
    private ConnectProperties config;
    private IotProtocolFactory protocolFactory;
    private IotMessageDecoder iotMessageDecoder;
    private Class<? extends ClientMessage> messageClass;

    public DefaultClientComponent(IotMessageDecoder iotMessageDecoder, ConnectProperties config
            , IotProtocolFactory protocolFactory, Class<? extends ClientMessage> messageClass) {
        this(messageClass.getSimpleName(), messageClass.getSimpleName(), iotMessageDecoder, config, protocolFactory, messageClass);
    }

    public DefaultClientComponent(String name, String desc, IotMessageDecoder iotMessageDecoder, ConnectProperties config
            , IotProtocolFactory protocolFactory, Class<? extends ClientMessage> messageClass) {
        this.name = name;
        this.desc = desc;
        this.config = config;
        this.messageClass = messageClass;
        this.protocolFactory = protocolFactory;
        this.iotMessageDecoder = iotMessageDecoder;
    }

    @Override
    protected SocketClient createClient() {
        return new TcpSocketClient(this, this.config) {
            @Override
            protected ChannelInboundHandler getClientProtocolDecoder() {
                return DefaultClientComponent.this.iotMessageDecoder.setMessageClass(messageClass());
            }
        };
    }

    @Override
    protected IotProtocolFactory createProtocolFactory() {
        return this.protocolFactory;
    }

    @Override
    public String getName() {
        return this.name;
    }

    @Override
    public String getDesc() {
        return this.desc;
    }

    @Override
    public Class<? extends ClientMessage> messageClass() {
        return this.messageClass;
    }

    public TcpClientComponent setName(String name) {
        this.name = name;
        return this;
    }

    public TcpClientComponent setDesc(String desc) {
        this.desc = desc;
        return this;
    }

    public ConnectProperties getConfig() {
        return config;
    }

    public TcpClientComponent setConfig(ConnectProperties config) {
        this.config = config;
        return this;
    }
}
